package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //判断session里有没有登录的信息
//        HttpSession session = request.getSession();
//        Employee employee = (Employee) session.getAttribute("SESSION_EMPLOYEE");
//        if (employee == null) {
//            //代表未登录,给前端返回相应的信息
//            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
//            String s = new ObjectMapper().writeValueAsString(resultInfo);
//            response.getWriter().write(s);
//            return false;
//        }
//        return true;

            //1、判断登录状态，如果已登录，则直接放行
            HttpSession session = request.getSession();
            Employee employee = (Employee) session.getAttribute("SESSION_EMPLOYEE");
            if (employee != null) {
                //将employ方法ThreadLocal
                EmployeeHolder.set(employee);
                return true;
            }

            //2、如果未登录,禁止通行,返回错误
            String json = JSON.toJSONString(ResultInfo.error("NOTLOGIN"));
            response.getWriter().write(json);
            return false;
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            EmployeeHolder.remove();
        }
}
